<?php

namespace app\admin\controller;

use app\common\model\AdminUser;
use app\Request;
use think\App;
use think\exception\ValidateException;
use think\facade\View;

class User extends AdminBase
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        $adminUser = new AdminUser();
        $userList  = $adminUser->limit(10)->order('id desc')->paginate(config('page.listRows'));
        View::assign("userList", $userList);
        View::assign('page',$userList->render());
        return View::fetch();
    }

    public function adduser(Request $request)
    {
        if ($request->isPost()) {
            try {
                validate(\app\validate\AdminUser::class)->scene('add')->check($request->post());

                $adminUser = new AdminUser();
                $rs        = $adminUser->save($request->post());
                if ($rs) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (ValidateException $e) {
                return $this->error($e->getMessage());
            }
        } else {

            return View::fetch();
        }
    }

    /**
     * 编辑
     * @param Request $request
     * @return string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(Request $request)
    {
        $id        = $request->request('id', 0, 'intval');
        $userInfo  = AdminUser::find($id);
        if(! $userInfo instanceof AdminUser){
            return $this->error('信息不存在');
        }
        if ($request->isPost()) {
            $data = $request->post();
            try {
                if($data['password'] == ''){//密码为空则不修改密码
                    unset($data['password']);
                    validate(\app\validate\AdminUser::class)->scene('edit_nopwd')->check($data);
                }else{
                    validate(\app\validate\AdminUser::class)->scene('edit')->check($data);
                }
                $rs        = $userInfo->save($data);
                if ($rs) {
                    return $this->success('编辑成功');
                } else {
                    return $this->error('编辑失败');
                }
            } catch (ValidateException $e) {
                return $this->error($e->getMessage());
            }
        } else {
            View::assign('statusList',AdminUser::$status);
            View::assign('userInfo', $userInfo);
            return View::fetch();
        }
    }

}
